package com.oss.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.oss.PMF;
import com.oss.model.Task;

/**
 * @author Xueqiang.Mi
 * @since 2010-7-14
 */
public class TaskService extends BaseService {

	public void addTasks(List<Task> tasks) {
		PersistenceManager pm = PMF.get();
		try {
			for (Task task : tasks) {
				if (!isExist(task.getLink())) {
					pm.makePersistent(task);
				}
			}
		} finally {
			pm.close();
		}
	}

	public Task get(Long id) {
		PersistenceManager pm = PMF.get();
		try {
			return pm.getObjectById(Task.class, id);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public Task getTaskByLink(String link) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Task.class);
			query.setFilter("link == :link");
			Collection<Task> c = pm.detachCopyAll((Collection<Task>) query.execute(link));
			if (c == null || c.isEmpty()) {
				return null;
			}
			return (Task) c.toArray()[0];
		} finally {
			pm.close();
		}
	}

	public boolean isExist(String link) {
		return getTaskByLink(link) != null;
	}

	@SuppressWarnings("unchecked")
	public List<Task> getTasks(Integer tasksNumber, String source) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Task.class);
			query.setFilter("status == 'ready' && source == :source");
			query.setOrdering("id ASCENDING");
			query.setRange(0, tasksNumber);
			Collection<Task> c = pm.detachCopyAll((Collection<Task>) query.execute(source));
			return new ArrayList<Task>(c);
		} finally {
			pm.close();
		}
	}

	/**
	 * @param task
	 */
	public void updateStatus(Long id) {
		PersistenceManager pm = PMF.get();
		try {
			Task task = pm.getObjectById(Task.class, id);
			task.setStatus("done");
		} finally {
			pm.close();
		}

	}

}
